package com.xw.util.zxing;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.xw.common.Const;
import com.xw.service.tool.oss.OssService;
import com.xw.util.AppUtil;
import com.xw.util.SpringBeanFactoryUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtil {


    /*
     * 定义二维码的宽高
     */
    private static int WIDTH = 300;
    private static int HEIGHT = 300;
    private static String FORMAT = "png";//二维码格式

    //生成二维码
    public static String createZxingqrCode(HttpSession session, String content) {
        //上传oss对象
        OssService ossService =(OssService) SpringBeanFactoryUtils.getBean("ossServiceImpl");
        String url = "";

        //定义二维码参数
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置容错等级
        hints.put(EncodeHintType.MARGIN, 2);//设置边距默认是5

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            // "/upload"是你自己定义的上传目录 本地就是demo/upload下的文件
            String realPath = session.getServletContext().getRealPath("/upload/");
            //判断文件夹是否存在，不存在就创建
            File filePath = new File(realPath);
            if (!filePath.exists()){
                filePath.mkdir();
            }
            String fileName = AppUtil.uuid() + "." + FORMAT;
            Path path = new File(realPath + fileName).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);//写到指定路径下

            //上传到oss ossService
            //转换成 MultipartFile 对象
            File file = new File(path.toString());
            FileInputStream fileInputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

            Map map = ossService.upload(multipartFile);

            if (map.get("code").equals(Const.SUCCESS_CODE)) {
                return map.get("url").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return url;
    }

    //读取二维码
    public static void readZxingQrCode() {
        MultiFormatReader reader = new MultiFormatReader();
        File file = new File("https://develop-kingsuper.oss-cn-hangzhou.aliyuncs.com/00304f4bda524cebb9d7efdfd06ee0ff.jpg");
        try {
            BufferedImage image = ImageIO.read(file);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
            Result result = reader.decode(binaryBitmap, hints);
            System.out.println("解析结果:" + result.toString());
            System.out.println("二维码格式:" + result.getBarcodeFormat());
            System.out.println("二维码文本内容:" + result.getText());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {

        File file = new File("https://develop-kingsuper.oss-cn-hangzhou.aliyuncs.com/00304f4bda524cebb9d7efdfd06ee0ff.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

        System.out.println(multipartFile.getName());
    }

}
